using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    static T _instance;
    static readonly object _lock = new();

    static bool _appliactionIsQuitting = false;

    public static T Instance
    {
        get
        {
            if (_appliactionIsQuitting)
            {
                Debug.LogWarning($"{typeof(T)} 实例已被销毁，应用正在退出");
                return null;
            }

            lock (_lock)
            {
                if (_instance == null)
                {
                    // 场景中查找现有实例
                    _instance = FindAnyObjectByType<T>();

                    // 场景中实例为空，则创建实例并添加
                    if (_instance == null)
                    {
                        var go = new GameObject($"{typeof(T).Name}");
                        _instance = go.AddComponent<T>();
                        DontDestroyOnLoad(go);
                        Debug.Log($"{typeof(T)} 创建单例实例");
                    }
                    else
                    {
                        DontDestroyOnLoad(_instance.gameObject);    // 确保现有实例持久化
                    }
                }

                return _instance;
            }
        }
    }

    /// <summary>
    /// 重写Awake实现初始化逻辑
    /// </summary>
    protected virtual void Awake()
    {
        lock (_lock)
        {
            if (_instance == null)
            {
                _instance = this as T;
                DontDestroyOnLoad(gameObject);
            }
            else if (_instance != this)
            {
                Debug.LogWarning($"检测到重复单例实例，销毁：{gameObject.name}");
                Destroy(gameObject);
            }
        }
    }

    /// <summary>
    /// 应用退出时释放资源
    /// </summary>
    protected virtual void OnApplicationQuit()
    {
        _appliactionIsQuitting = true;
        if (_instance == this)
        {
            _instance = null;
        }
        Destroy(gameObject);
    }
}